package com.yishan.gulimall.springsecurity.handler;

import com.alibaba.fastjson2.JSON;
import com.yishan.gulimall.springsecurity.config.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 授权失败处理器
 */
@Component
public class AuthenticationAcceptHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("text/html;charset=utf-8");
        String jsonString = JSON.toJSONString(R.error("当前用户没有访问权限"));
        httpServletResponse.getWriter().write(jsonString);
    }
}
